package com.weixin.IOStream;

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName FileClass
 * @Description file操作类
 * @date 2022/2/17 10:08
 * @author: wx
 * @Version 1.0
 */
public class FileClass {

    @Test
    public void FileTest() throws IOException {
        File file = new File("Hello.txt");
        if (file.exists()) {
            System.out.println("文件存在:" + file.getAbsolutePath());
            boolean b = file.setReadable(true);
            if (b) {
                System.out.println("设置文件可读成功！");
                OutputStream outputStream = new FileOutputStream(file);
                OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
                writer.append("我将生活看做幻光，生在幻光，长在幻光，死在幻光！");
                writer.append("\r\n");
                writer.append("生活一向如此");
                writer.close();
                outputStream.close();
                InputStream inputStream = new FileInputStream(file);
                InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                StringBuilder sb = new StringBuilder();
                while (reader.ready()) {
                    sb.append((char) reader.read());
                }
                System.out.println(sb.toString());
                inputStream.close();
            } else {
                System.out.println("权限问题，文件不可修改权限");
            }
        } else {
            boolean newFile = file.createNewFile();
            if (newFile) {
                System.out.println("文件不存在，创建成功！");
            } else {
                System.out.println("文件创建失败！");
            }
        }
    }
}
